import java.util.Arrays;

/**
 * @author: gao
 * @create-date: 2025/3/5 18:50
 */

public class Heap {
    public int[] elem;
    public int usedSize;

    public Heap() {
        elem = new int[10];
    }

    public void Initial(int[] array) {
        for (int i = 0; i < array.length; i++) {
            elem[i] = array[i];
            usedSize++;
        }
    }

    public void CreateHeap() {
        for (int parent = (usedSize - 1 - 1) / 2; parent >= 0; parent--) {
            ShiftDown(parent, usedSize);
        }
    }

    private void ShiftDown(int parent, int usedSize) {
        int child = 2 * parent + 1;
        while (child < usedSize) {
            if (child + 1 < usedSize && elem[child] < elem[child + 1]) {
                child++;
            }
            //走到这里，child下标一定是左右孩子最大值的下标
            if (elem[child] > elem[parent]) {
                //交换
                swap(parent, child);
                parent = child;
                child = 2 * parent + 1;
            } else {
                break;
            }
        }
    }

    private void swap(int i, int j) {
        int tmp = elem[i];
        elem[i] = elem[j];
        elem[j] = tmp;
    }

    //插入
    public void offer(int val) {
        if (isFull()) {
            elem = Arrays.copyOf(elem, 2 * elem.length);
        }
        elem[usedSize] = val;
        //调整
        ShiftUp(usedSize);
        usedSize++;
    }

    private void ShiftUp(int child) {
        int parent = (child - 1) / 2;
        while (parent >= 0) {
            if (elem[child] > elem[parent]) {
                swap(child, parent);
                child = parent;
                parent = (child - 1) / 2;
            } else {
                break;
            }
        }
    }

    public boolean isFull() {
        return elem.length == usedSize;
    }

    //删除
    public int poll() {
        if(isEmpty()){
            return -1;
        }
        int OldValue = elem[0];
        usedSize--;
        swap(0,usedSize);
        ShiftDown(0,usedSize);
        return OldValue;
    }

    public boolean isEmpty() {
        return usedSize == 0;
    }
}
